# -*- coding: utf-8 -*-
"""
****************************
@Time    : 2021/4/25 11:43
@Author  : Candy
@File    : normal.py
****************************
"""
import datetime
import hashlib
import re
import time

from config.db import NOISE


def create_logger(prefix, log_file, show):
    """
    创建日志对象，调试阶段可以使用
    :return:
    """
    import logging.handlers
    logger = logging.getLogger(prefix)
    logger.setLevel(logging.DEBUG)
    # 建立一个file_handler来把日志记录在文件里，级别为debug以上
    fh = logging.handlers.RotatingFileHandler(filename=log_file, maxBytes=5 * 1024 * 1024, backupCount=5, mode='a',
                                              encoding='utf-8')
    fh.setLevel(logging.DEBUG)
    # 建立一个stream_handler来把日志打在CMD窗口上，级别为debug以上
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    # 设置日志格式
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    # 将相应的handler添加在logger对象中
    if show:
        logger.addHandler(ch)
    logger.addHandler(fh)
    return logger


def text2md5(source_data) -> str:
    source_data = source_data if isinstance(source_data, str) else str(source_data)
    h = hashlib.md5()
    h.update(source_data.encode('utf-8'))
    return h.hexdigest()


def serializer_pwd(pwd):
    return text2md5(pwd + NOISE)


def build_aid():
    res = (text2md5(time.time()) + str(time.time()).split('.')[0]).split()
    return ''.join(res)


def change_content(con):
    res = re.sub('(?P<all>!\[(?P<c>.*?)\]\((?P<src>.*?)\))', change, con)
    return res


def change(regexp):
    src = regexp.group('src')
    con = regexp.group('c')
    return f'<img src="{src}" alt="{con}" style="width:50%; float:center">'


def time_change(old_time):
    print(old_time)
    gmt_format = '%a, %d %b %Y %H:%M:%S GMT'
    new_time = datetime.datetime.strptime(old_time, gmt_format)
    return new_time

